<template>
  <div id="gmap" style="overflow-y: scroll;" :style="{height: clientHeight}">
    <div class="map-header">
      <div @click="handleCity"  style="padding-left: 0.2rem; padding-right: 0.2rem;display: flex;align-items: center;">
        <span style="display: inline-block; margin-right: 0.2rem">{{ city }}</span>
        <i class="icon icon-angle-down" style="font-size: 0.16rem; color: #999;"></i>
      </div>
      <div style="flex: 1;">
        <x-input @click.native="handlePOI" @input="handlePOI" v-model="searchStart" placeholder="输入地址查询" style="border-left: 1px solid #eee; border-right: 1px solid #eee; padding: 0.1rem 0.2rem;">
        </x-input>
        <div id="poiInfo" style="position: fixed; z-index: 999999;"></div>
      </div>
      <div style="width: 1rem; text-align: center;line-height: 0.95rem" @click="handleCancle">取消</div>
    </div>
    <div class="tab-header" v-show="isShowTag">
      <tab v-model="tabIndex" :line-width="lineWidth" custom-bar-width="1.6rem"  :active-color="lineWidth? '#ff5722' : '#666'">
        <tab-item @on-item-click="showSystemAddress('history')">历史地址</tab-item>
        <tab-item @on-item-click="showSystemAddress('collection')">收藏地址</tab-item>
        <tab-item @on-item-click="showSystemAddress('nearby')">附近地址</tab-item>
      </tab>
    </div>
    <div v-show="showMap2" id="amapContainerGlobal" :style="{height: clientHeight}">
      <div class="fixed-address" :class="{'show-fixed-address': showMapAddress}">
        <div class="fixed-address-form">
          <div><i class="icon icon-house"></i></div>
          <div class="flex-auto">
            <x-input placeholder="系统定位地址，不可填写" v-model="formItem.firstAddress" readonly :show-clear="false"></x-input>
            <x-input @on-focus="inputFocus" @on-blur="inputBlur" placeholder="详细地址(选填，例:3栋2单元505)" v-model="formItem.detailsAddress"></x-input>
          </div>
        </div>
        <div class="fixed-address-form" v-show="isCheckPhone">
          <div class="flex-auto"><x-input @on-focus="inputFocus" @on-blur="inputBlur" :max="11" v-model="formItem.phone" type="tel" placeholder="请填写手机号码" style="border-top: 1px solid #eee;"></x-input></div>
        </div>
        <div class="fixed-address-form">
          <x-button type="primary" action-type="button" style="border-radius: 0;" @click.native="handleSub">确认</x-button>
        </div>
      </div>

    </div>
    <div v-transfer-dom>
      <popup v-model="showCity">
        <div class="popup0">
          <div class="picker-btn">
            <div style="height: 0.9rem; padding-right: 0.5rem;" @click="showCity = false">取消</div>
            <div style="color: #222; font-size: 0.32rem;">选择所在地区</div>
            <div class="text-orange" style="height: 0.9rem;padding-left: 0.5rem;" @click="handlePickerCity">确定</div>
          </div>
          <picker :data="area" :columns=3 :fixed-columns="columns" v-model="ssq" @on-change="changeSsq" ref="pickerarea"></picker>
        </div>
      </popup>
    </div>
    <div v-show="showSearch2" :style="{marginTop: isShowTag? '1.85rem': '1.1rem'}" style="padding: 0.2rem 0.3rem; background: #f3f4f5;overflow-y: scroll;">
      <ul style="box-shadow: 0 0 0.1rem rgba(0,0,0,0.15); background: #fff;" v-if="searchPOIObj.length > 0">
        <li
          style="height: 1.06rem; display: flex;align-items: center; padding: 0 0.25rem; border-bottom: 1px solid #eee;"
          :key="index"
          v-for="(item, index) in searchPOIObj"
          @click.naitve="handleArea(item)">
          <div style="width: 0.6rem"><i class="icon icon-map" style="font-size: 0.34rem; color: #999;"></i></div>
          <div style="flex: 1;">
            <p class="overflowtext">{{ item.name }}</p>
            <p style="color: #888;overflow: hidden; height: 0.38rem;" class="overflowtext"><small>{{ item.district }}{{ item.address }}{{ item.detailsAddress }} {{ item.phone }}</small></p>
          </div>
        </li>
      </ul>
      <div v-else style="text-align: center; color: #bbb; margin-top: 1rem;">
        <p><i class="icon icon-gantanhao" style="font-size: 0.7rem;"></i></p>
        <p style="font-size: 0.3rem;">没有找到相关地址，请输入地址查询</p>
      </div>
    </div>
  </div>
</template>

<script>
  import { TransferDom } from 'vux'
  import {setProvinceCode, setCityCode} from '../libs/fn'
  var globalMap
  export default{
    directives: {
      TransferDom
    },
    name: 'gmap',
    props: {
      isCheckPhone: {
        type: Boolean,
        default: true
      },
      mapAddress: Boolean,
      mapdata: Object,
      boxChange: Boolean,
      columns: {
        type: Number,
        default: 2
      },
      isOpen: Boolean,
      isShowTag:{
        type: Boolean,
        default: true
      },
      isDingwei:{
        type: Boolean,
        default: true
      },
      index: {
        type: [String, Boolean, Number],
        default: 0
      },
      type: String
    },
    computed: {
      clientHeight() {
        return document.documentElement.clientHeight + 'px'
      },
      addressType() {
        return {
          xiaojiansudi: 1,
          tongchengkuaiche: 2,
          xianshitong: 3,
          tongchenggongpei: 4,
          kuaidibao: 5,
          tongchengzhuanche: 6,
          lingdanzhuanxian: 7,
          chengjizhengche: 8
        }
      }
    },
    data() {
      return {
        historyShouUrl: $config.host + '/api/Useraddr/getHistoryShouaddress',
        count: 0,
        tabIndex: -1,
        lineWidth: 0,
        lastAdcode: '',
        collectionAddress: [],
        historyAddress: [],
        historyClickCount: 0,
        collectionClickCount: 0,
        cpoint: [],
        ssq: this.$store.state.ssq,
        area: [],
        start: {
          firstAddress: 'township...',
          phone: this.$store.state.userInfo.phone,
          lng: '',
          lat: '',
          province: '',
          city: '',
          area: '',
          provinceCityAreaName: ''
        },
        showMapAddress: false,
        showCity: false,
        showMap2: true,
        showSearch2: false,
        searchCityName: '',
        searchPOIObj: [],
        searchStart: '',
        city: this.$store.state.city,
        formItem: {
          firstAddress: '',
          detailsAddress: '',
          phone: '',
          lng: '',
          lat: '',
          province: '',
          city: '',
          area: '',
          provinceCityAreaName: '',
        }
      }
    },
    beforeUpdate() {
      if(this.formItem.lat && this.formItem.lng) {
        globalMap.setZoomAndCenter(16, [this.formItem.lng, this.formItem.lat])
      }
    },
    watch: {
      isOpen: function (val) {
        if(val && this.count == 0){
          this.$http.get('../../static/area1.json').then((res) => {
            this.area = res.data
          }).catch((error) => {
          })
        }
        this.count++
        if(val && !this.mapdata.lat) {
          this.tabIndex = 0
          this.showSystemAddress('history')
        } else {
          this.tabIndex = -1
        }
      },
      start: {
        handler: function (val) {
          this.$emit('start', val)
        },
        deep: true
      },
      mapAddress: function (val) {
        setTimeout(() => {
          this.showMapAddress = val
        }, 400)
      },
      mapdata: function (val) {
        this.formItem = JSON.parse(JSON.stringify(val))
      },
      boxChange: function (val) {
        this.showMap2 = !val
        this.showSearch2 = val
      },
      columns: function (val) {
        if(val == '3') {
          this.ssq.push(this.lastAdcode)
          this.$store.commit('setSSQ', this.ssq)
        }
      }
    },
    mounted() {
      //加载地图，调用浏览器定位服务
      globalMap = new AMap.Map('amapContainerGlobal', {
        resizeEnable: true
      })
      if(this.$store.state.startAddressInfo.lng && this.$store.state.startAddressInfo.lat) {
        return
      }
      //如果有默认地址的话，先使用默认地址，不用定位
      this.$http.post($config.host + '/api/Useraddr/getDefaultAddress', qs.stringify({
        uid: this.$store.state.userInfo.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then(res => {
        const { code, data } = res.data
        if(code == 1) {
          this.city = data.city
          this.start.firstAddress = data.addr1
          this.start.detailsAddress = data.addr2
          this.start.phone = data.phone
          this.start.lng = data.lng
          this.start.lat = data.lat
          const cityCode = (data.city_code).toString()
          let province = cityCode.substring(0, 2) + '0000'
          let city = cityCode.substring(0, 4) + '00'
          this.ssq = [province, city, cityCode]
          this.$store.commit('setSSQ', this.ssq)

          this.lastAdcode = cityCode
          this.start.province = province
          this.start.city = city
          this.start.area = cityCode

          this.start.provinceCityAreaName = data.provice + data.city + data.area

          this.$store.commit('setStartAddress', this.start)
          this.$store.commit('setCity', this.city)
          this.setMarker(data.lng, data.lat)
        } else if (code == '3') {
          this.$vux.toast.text($config.loginErrMsg, 'middle')
          this.$router.push({path: '/logout'})
        } else {
          this.setLocation()
        }
      })

    },
    methods: {
      inputFocus() {
        const u = navigator.userAgent;
        const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        if(isAndroid) {
          this.$emit('setab', 'absolute')
        }

      },
      inputBlur() {
        const u = navigator.userAgent;
        const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        if(isAndroid) {
          this.$emit('setab', 'fixed')
        }
      },
      setLocation() {
        let geolocation
        globalMap.plugin('AMap.Geolocation', () => {
          geolocation = new AMap.Geolocation({
            maximumAge: 0,
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 20000,          //超过20秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB',
            showCircle: false        //定位成功后用圆圈表示定位精度范围，默认：true
          })
          globalMap.addControl(geolocation)
          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', this.onComplete)//返回定位信息
          AMap.event.addListener(geolocation, 'error', this.onError)      //返回定位出错信息

        })
      },
      //解析定位结果
      onComplete(data) {
        const lnglatXY = [data.position.lng, data.position.lat] //已知点坐标
        this.start.lng = data.position.lng
        this.start.lat = data.position.lat
        this.setAddress(lnglatXY)
        this.cpoint = lnglatXY

      },
      onError(data) {
        let errorMsg = data.info == 'FAILED'? '途鸟未获取到您的定位权限，请到设置中开启定位': '您的浏览器不支持定位，请手动输入'
        const _this = this
        if(this.isDingwei) {
          this.$vux.confirm.show({
            title: '<i class="icon icon-gantanhao"></i>',
            content: errorMsg,
            confirmText: '输入发货地址',
            cancelText: '我知道了',
            onConfirm() {
              _this.$emit('gpsconfirm')
              _this.showSearch2 = true
              _this.showMap2 = false
              _this.handlePOI()
            }
          })
        }
        this.start = {
          firstAddress: '定位失败，请手动输入',
          phone: this.$store.state.userInfo.phone,
          lng: '',
          lat: ''
        }
        this.ipAccessCity()
      },
      geocoder_CallBack(data) {
        const addressData = data.regeocode.addressComponent

        var replaceaddress = addressData.province+addressData.city+addressData.district+addressData.township; //省市区街道
        var address = data.regeocode.formattedAddress
        address = address.replace(replaceaddress, '') //去除省市区,显示简短地址
        this.city = addressData.city
        this.start.firstAddress = address
        let province = addressData.adcode.substring(0, 2) + '0000'
        let city = addressData.adcode.substring(0, 4) + '00'
        this.ssq = [province, city, addressData.adcode]
        this.$store.commit('setSSQ', this.ssq)

        this.lastAdcode = addressData.adcode
        this.start.province = province
        this.start.city = city
        this.start.area = addressData.adcode

        this.start.provinceCityAreaName = addressData.province+addressData.city+addressData.district

        this.$store.commit('setStartAddress', this.start)

        this.$store.commit('setCity', this.city)


      },
      setAddress(lnglatXY) {
        var geocoder = new AMap.Geocoder({
          radius: 500,
          extensions: "all"
        });

        geocoder.getAddress(lnglatXY, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.geocoder_CallBack(result);
          }
        });

        this.setMarker(lnglatXY[0], lnglatXY[1])

      },

      //定位失败后通过IP获取当前所在市
      ipAccessCity() {
        //实例化城市查询类
        AMap.plugin('AMap.CitySearch',() => {//异步
          let citysearch = new AMap.CitySearch();
          //自动获取用户IP，返回当前城市
          citysearch.getLocalCity((status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.city && result.bounds) {
                let province = result.adcode.substring(0, 2) + '0000'
                let area = result.adcode.substring(0, 5) + '1'
                const citybounds = result.bounds
                this.city = result.city
                this.ssq =  [province, result.adcode, area]
                this.$store.commit('setSSQ', this.ssq)
                this.$store.commit('setCity', this.city)
                this.lastAdcode = area
                //地图显示当前城市
                globalMap.setBounds(citybounds);
              }
            }
          })
        })
      },

      //点击取消按钮时
      handleCancle() {
        this.inits()
        this.$emit('cancle')
      },

      //点击城市时
      handleCity() {
        this.showCity = true
        this.searchStart = ''
      },

      handlePOI() {
        this.lineWidth = 0
        this.showMap2 = false
        this.showCity = false
        this.showSearch2 = true
        let searchcity = this.searchStart || this.city
        const len = this.columns == 2? 1: 2
        const adcode = this.ssq[len]
        AMap.service(["AMap.Autocomplete"], () => {
          var placeSearch = new AMap.Autocomplete({ //构造地点查询类
            datatype: 'poi',
            city: adcode
          });
          placeSearch.search(searchcity, (status, result) => {
            let poi = result.tips
            if(searchcity == this.city){
              poi.splice(0, 1)
            }
            this.searchPOIObj = poi
          })
        });
      },

      handleSub() {
        if (!this.formItem.lng || !this.formItem.lat) {
          this.$vux.toast.text('请通过地址栏搜索选择地址', 'middle')
          return false
        }

        if (!this.formItem.firstAddress) {
          this.$vux.toast.text('请输入地址', 'middle')
          return false
        }

        if(this.isCheckPhone) {
          if (!this.formItem.phone) {
            this.$vux.toast.text('请输入手机号码', 'middle')
            return false
          }

          const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
          const tel = this.formItem.phone
          if(!reg.test(tel)){
            this.$vux.toast.text('手机号码不正确', 'middle')
            return false
          }
        }
        if(this.isDingwei && this.index === null){
          if(this.$store.state.cityCode == this.formItem.area){
            this.$store.commit('setCityCodeCount')
          }
          this.$store.commit('setCityCode', this.formItem.area)

        }

        this.formItem.detailsAddress = this.formItem.detailsAddress? this.formItem.detailsAddress: ''
        this.$emit('submit', this.formItem)

        this.handleCancle()
        this.formItem = {
          firstAddress: '',
          detailsAddress: '',
          phone: '',
          lng: '',
          lat: '',
          province: '',
          city: '',
          area: '',
          provinceCityAreaName: ''
        }
      },

      //选择查询的地址后
      handleArea(item) {
        this.showMap2 = true
        this.showCity = false
        this.showSearch2 = false
        //this.searchStart = ''
        console.log(item.name.indexOf(item.district))
        this.formItem.provinceCityAreaName = item.name.indexOf(item.district) > -1? '': item.district
        this.formItem.firstAddress = item.name

        if(item.phone) {
          this.formItem.phone = item.phone
        }
        this.formItem.detailsAddress =  item.detailsAddress
        this.formItem.lng = item.location.lng
        this.formItem.lat = item.location.lat
        if(!item.adcode) {
          const lnglatXY = [item.location.lng, item.location.lat]
          var geocoder = new AMap.Geocoder({
            radius: 500,
            extensions: "all"
          });
          geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              item.adcode = result.regeocode.addressComponent.adcode
              this.formItem.province = setProvinceCode(item.adcode)
              this.formItem.city = setCityCode(item.adcode)
              this.formItem.area = item.adcode
            }
          });
        } else {
          this.formItem.province = setProvinceCode(item.adcode)
          this.formItem.city = setCityCode(item.adcode)
          this.formItem.area = item.adcode
        }
        this.setMarker(item.location.lng, item.location.lat)
      },
      //加定位标记点
      setMarker(lng, lat) {
        globalMap.setZoomAndCenter(16, [lng, lat])
        // 在新中心点添加 marker
        new AMap.Marker({
          map: globalMap,
          position: [lng, lat]
          //animation: 'AMAP_ANIMATION_BOUNCE'
        })
      },
      //
      changeSsq(val) {
        if(val.length == 3) {
          this.lastAdcode = val[2]
        }
      },
      // 选择联动
      handlePickerCity() {
        let area = this.$refs.pickerarea && this.$refs.pickerarea.getNameValues()
        let areaArr = area.split(' ')
        this.city = areaArr[areaArr.length - 1]
        this.showCity = false
        this.$store.commit('setCity', this.city)
        this.handlePOI()
      },
      //获取收藏和历史地址
      getDBAddress(url, tag) {
        const uid = this.$store.state.userInfo.uid
        this.$http.post(url, qs.stringify({
          uid,
          type: this.addressType[this.type],
          client: $config.client_type,
          device: $config.device_type,
          token: this.$store.state.userInfo.token
        })).then(res => {
          const { code, data } = res.data
          if(code == 1 && data) {
            const data_list = data.data_list
            let obj = []
            data_list.forEach(item => {
              obj.push({
                name: item.addr1,
                location: {
                  lng: item.lng,
                  lat: item.lat
                },
                adcode: (item.city_code).toString(),
                detailsAddress: item.addr2,
                phone: item.phone,
                district: tag == 'collection'? item.provice + item.city + item.area: ''
              })
            })
            if(tag == 'history') {
              this.historyAddress = obj
              this.historyClickCount++
            } else if (tag == 'collection') {
              this.collectionAddress = obj
              this.collectionClickCount++
            }
            this.searchPOIObj = obj
          }
        })
      },
      //点击tab标签切换地址时
      showSystemAddress(tag) {
        this.showMap2 = false
        this.showSearch2 = true
        this.lineWidth = 2
        this.searchPOIObj = []
        if(tag == 'history') {
          if(this.historyClickCount) {
            this.searchPOIObj = this.historyAddress
            return
          }
          this.getDBAddress(this.historyShouUrl, tag)

        } else if(tag == 'collection') {
          if(this.collectionClickCount) {
            this.searchPOIObj = this.collectionAddress
            return
          }
          this.getDBAddress($config.host + '/api/Useraddr/listAddress', tag)
        } else if(tag == 'nearby') {
          if(this.cpoint.length) {
            this.getNear()
          } else {
            let geolocation
            globalMap.plugin('AMap.Geolocation', () => {
              geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 20000,          //超过20秒后停止定位，默认：无穷大
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition:'RB',
                showCircle: false        //定位成功后用圆圈表示定位精度范围，默认：true
              })
              globalMap.addControl(geolocation)
              geolocation.getCurrentPosition()
              AMap.event.addListener(geolocation, 'complete', (data) => {
                const lnglatXY = [data.position.lng, data.position.lat] //已知点坐标
                this.cpoint = lnglatXY
                this.getNear()
              })//返回定位信息

            })

          }

        }
      },
      getNear() {
        AMap.service(["AMap.PlaceSearch"], () => {
          const placeSearch = new AMap.PlaceSearch({ //构造地点查询类
            pageSize: 15,
            pageIndex: 1,
            city: this.city
          })
          placeSearch.searchNearBy('', this.cpoint, 200, (status, result) => {
            if(status == 'complete') {
              this.searchPOIObj = result.poiList.pois
            }
          })
        })
      },
      //初始化
      inits() {
        setTimeout(() => {
          this.showMap2 = !this.boxChange
          this.showCity = false
          this.showSearch2 = this.boxChange
        }, 400)
      }
    }
  }
</script>

<style scoped>
  .map-header{
    position: fixed;
    z-index: 9999999;
    top: 0;
    left: 0;
    right: 0;
    height: 1rem;
    background: #fff;
    display: flex;
    align-items: center;
    transition: all 0.4s;
    box-shadow: 0px 0px 0.1rem rgba(0, 0, 0, 0.15);
  }
  .tab-header{
    position: fixed;
    z-index: 9999999;
    top: 1rem;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #eee;
    transition: all 0.4s;
  }
  .fixed-address{
    position: fixed;
    z-index: 9;
    bottom: 0.45rem;
    left: 0.3rem;
    right: 0.3rem;
    background: #fff;
    box-shadow: 0px 0px 0.1rem rgba(0, 0, 0, 0.15);
    opacity: 0;
    transition: all 0.4s;
  }
  .show-fixed-address{
    opacity: 1;
  }
  .fixed-address .icon{
    color: #fc9153;
    font-size: 0.7rem;
    display: inline-block;
    margin-left: 0.2rem;
  }
  .fixed-address-form{
    display: flex;
    align-items: center;
  }
</style>
